package icu.twtool.generator

import icu.twtool.entity.AdditionBinaryEquation
import icu.twtool.entity.BinaryEquation
import icu.twtool.entity.SubtractionBinaryEquation
import kotlin.math.max
import kotlin.random.Random
import kotlin.random.nextInt

/**
 * 算式生成器
 * @param numberRange 习题范围(default: [0, 100])
 */
class EquationGenerator(private val numberRange: IntRange = 0..100) {

    private val len = max(numberRange.last.toString().length, numberRange.first.toString().length)

    /**
     * 生成操作数
     */
    private fun generateOperands(): Int {
        return Random.nextInt(numberRange)
    }

    /**
     * 生成加法算式
     */
    fun generateAdditionEquation(): BinaryEquation {
        while (true) {
            AdditionBinaryEquation(generateOperands(), generateOperands(), len).let {
                if (it.answer() in numberRange) {
                    return it
                }
            }
        }
    }

    /**
     * 生成减法算式
     */
    fun generateSubtractionEquation(): BinaryEquation {
        while (true) {
            SubtractionBinaryEquation(generateOperands(), generateOperands(), len).let {
                if (it.answer() in numberRange) {
                    return it
                }
            }
        }
    }

    /**
     * 生成随机算式
     */
    fun generateRandomEquation(): BinaryEquation {
        return if (Random.nextBoolean()) generateAdditionEquation()
        else generateSubtractionEquation()
    }
}